/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.springapp.controller;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.springapp.model.User;
import com.springapp.service.impl.UserServiceImpl;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import java.util.List;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;

import org.springframework.web.bind.annotation.ResponseBody;
import com.springapp.util.ControllerUtil;

/**
 *
 * @author Лерок
 */
@Controller
@RequestMapping("/")
public class UserController {

    private final Logger log = LoggerFactory.getLogger(UserController.class);
    @Autowired
    private UserServiceImpl usi;

    @RequestMapping(value = "/user", method = RequestMethod.GET)
    public @ResponseBody
    String getUsersName() {
        List<User> users = usi.getAll();
        String[] userNames = new String[users.size()];
        for (int i = 0; i < users.size(); i++) {
            userNames[i] = users.get(i).getName();
        }
        log.info("users arr" + users);
        GsonBuilder builder = new GsonBuilder();
        Gson gson = builder.create();
        String userJson = gson.toJson(userNames);
        log.info(userJson);
        return ControllerUtil.printSuccess(userJson);
    }

    @RequestMapping(value = "/user", method = RequestMethod.POST)
    public @ResponseBody
    String create(@RequestBody String json) {
        Gson gson = new Gson();
        User userJson = gson.fromJson(json, User.class);
        User user = new User();
        user.setName(userJson.getKey());
        user.setLogin(userJson.getLogin());
        user.setPassword(userJson.getPassword());
        user.setKey(null);
        user.setRole(userJson.getRole());
        usi.create(user);
        return ControllerUtil.printSuccess(json);
    }

    /**
     *
     * @param login
     * @return
     */
    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public @ResponseBody
    String getByLoginAndPassword(@RequestParam String login,
            @RequestParam String password) {
        User user = usi.findByLoginAndPassword(login, password);
        if (user == null) {
            return ControllerUtil.printError();
        }
        GsonBuilder gsonBuilder = new GsonBuilder();
        Gson gson = gsonBuilder.create();
        String json = gson.toJson(user);
        log.info(json);
        return ControllerUtil.printSuccess(json);
    }
}
